package com.buka.blog.controller;

import com.buka.blog.entity.Blog;
import com.buka.blog.service.BlogService;
import com.buka.common.Page;
import com.buka.common.ResultJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/blog/page")
public class PageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取分页参数
        String pageNumStr = req.getParameter("pageNum");
        String pageSizeStr = req.getParameter("pageSize");
        if (null == pageNumStr) {
            pageNumStr = "1";
        }
        if (null == pageSizeStr) {
            pageSizeStr = "5";
        }
        int pageNum = Integer.parseInt(pageNumStr);
        int pageSize = Integer.parseInt(pageSizeStr);

        //查询数据
        BlogService blogService = new BlogService();
        //分页查询的结果集
        List<Blog> list = blogService.list(pageNum, pageSize);
        //渲染分页组件还需要查询总记录数
        long totalCount = blogService.totalCount();
        //封装分页数据
        Page<List<Blog>> blogPage = new Page<>();
        blogPage.setData(list);//设置数据结果集
        blogPage.setPageNum(pageNum);//当前页码
        blogPage.setPageSize(pageSize);//每页记录数
        blogPage.setTotalCount((int) totalCount);//总记录数
        //计算总页数
        long pageTotal = totalCount / pageSize;
        //除不尽，则总页数加1
        pageTotal += totalCount % pageSize == 0 ? 0 : 1;
        blogPage.setTotalPage((int) pageTotal);
        //返回数据
        PrintWriter writer = resp.getWriter();
        writer.print(ResultJson.success(blogPage));
    }
}
